找传奇、传世资源到传世资源站!

TCP简单通讯

8.5玩家评分(1人评分)
下载后可评
介绍 评论 失效链接反馈

初学网络编程,需要了解的tcp的socket的小例子
from clipboardTCP简单通讯 C#网络编程-第2张from clipboard
private void AcceptMessage()
        {
            while (true)
            {
                try
                {
                    NetworkStream netStream = new NetworkStream(newSocket);
                    
                    byte[] datasize = new byte[4];
                    netStream.Read(datasize, 0, 4);
                    int size = System.BitConverter.ToInt32(datasize, 0);  //得到缓冲区数据的大小
                    
                    Byte[] message = new byte[size];
                    int dataleft = size;
                    int start = 0;
                    
                    while (dataleft > 0)   //逐字节读取数据
                    {
                        int recv = netStream.Read(message, start, dataleft);  
                        start = recv;
                        dataleft -= recv;
                    }

                    this.rtbAccept.Rtf = System.Text.Encoding.Unicode.GetString(message);
                }
                catch
                {
                    this.lbState.Items.Add("与客户断开连接");
                    break;
                }
            }

        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            string str = this.rtbSend.Rtf;
            int i = str.Length;
            if (i == 0)
            {
                return;
            }
            else
            {
                //因为str为Unicode编码,每个字符占2字节,所以实际字节数应*2
                i *= 2;
            }

            byte[] datasize = new byte[4];
            //将32位整数值转换为字节数组
            datasize = System.BitConverter.GetBytes(i);
            byte[] sendbytes = System.Text.Encoding.Unicode.GetBytes(str);
            try
            {
                NetworkStream netStream = new NetworkStream(newSocket);
                netStream.Write(datasize, 0, 4);
                netStream.Write(sendbytes, 0, sendbytes.Length);
                netStream.Flush();

                this.rtbSend.Rtf = "";
            }
            catch
            {
                MessageBox.Show("无法发送!");
            }
        }

        private void btnStopListen_Click(object sender, EventArgs e)
        {
            this.btnStartListen.Enabled = true;
            try
            {
                socket.Shutdown(SocketShutdown.Both);   //此处总产生异常
                socket.Close();

                if (newSocket.Connected)
                {
                    newSocket.Close();
                    thread.Abort();

                    this.lbState.Items.Add("停止监听,与客户断开连接");
                }
            }
            catch
            {
                MessageBox.Show("监听尚未开始,关闭无效!");
            }
        }

评论

发表评论必须先登陆, 您可以 登陆 或者 注册新账号 !


在线咨询: 问题反馈
客服QQ:174666394

有问题请留言,看到后及时答复